<template>
    <div class="edit-broad">
        <Header 
        :title="broadCastTitle"
         @backClick="backClick"
         @inputChange="inputChange">
        </Header>
         <div class="select-people" @click="selectPeopleClick">
            <div class="title">
                选择数字人
            </div>
            <div class="no-people" v-if="!peopleInfo.name">
                <img  src="http://static.yuandiancnc.com/avatar_cover/avatar1.png" />
                <div class="mark">
                    <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
                </div>
            </div>
            <div class="people" v-if="peopleInfo.name">
                <img :src="peopleInfo.coverSmall" />
                <span>{{peopleInfo.name}}</span>
            </div>
            <Label v-if="peopleInfo.videoCnt" class="video-num" label="该数字人视频数" :num="peopleInfo.videoCnt" :img="ic_bo" :imgWidth="50" :isShowImg="true" ></Label>
            <Label style="flex: 1;"  v-if="peopleInfo.videoLength"  label="该数字人视频长度" :num="peopleInfo.videoLength" :img="ic_amount" :imgWidth="50" :isShowImg="true"></Label>
         </div>
         <div class="main-video">
            <div class="left">
                <videoSelect ref="videoSelectRef" key="video" :avatarName="avatarName" :isGetList="isGetList" :isShowTitle="true" :select-list="selectVideotListFirst" @select="selectVideo"/>
            </div>
            <div class="line"></div>
            <div class="right">
                <div class="table-name">已选视频</div>
                <div class="table-header">
                    <div class="switch">
                        <span>是否随机开启</span>
                        <el-switch v-model="mainVideoRandom" class="ml-2" />
                    </div>
                    <span>视频数量：{{ selectVideotListFirst.length }}</span>
                    <span>总时长: {{  timer }}</span>
                </div>
                <div class="table-list"> 
                    <template v-if="!mainVideoRandom">
                        <draggable 
                            :list="selectVideotListFirst"
                                item-key="id"
                                animation="300"
                            >
                            <template #item="{ element }">
                                <TableItem key="tableitem"  :id="element.id" :name="element.title" :time="`时长${element.length}分钟`" :type="element.type" @iconClick="iconFirstClick($event, element)"></TableItem>
                            </template>
                        </draggable>
                    </template>
                    <template v-else>
                        <TableItem key="table-item1" v-for="v_item in selectVideotListFirst" :id="v_item.id" :name="v_item.title" :time="`时长${v_item.length}分钟`" :type="v_item.type" @iconClick="iconFirstClick($event,v_item)"></TableItem>
                    </template>
                </div>
            </div>  
         </div>
         <div class="answer" :style="{height: answerOpen? '600px': '50px'}">
            <div class="answer-title">
                设置自动回复
                <div class="icon" @click="answerIconClick">
                    <el-icon v-if="answerOpen"><ArrowUp /></el-icon>
                    <el-icon v-else><ArrowDown /></el-icon>
                </div>
            </div>
            <div class="keyword-list" v-if="answerOpen">
                <div class="keyword-header">
                    <span>规则数：{{ rulesList.length }}</span>
                    <el-button class="add-btn btn" :icon="Plus" color="#BC81FC" @click="addRules('KEY')">添加关键词</el-button>
                    <el-button class="btn" :icon="Plus" color="#BC81FC" @click="addRules('GIFT')">礼物规则</el-button>
                </div>
                <div class="keyword-item" v-for="(item, index) in rulesList">
                    <!-- <el-icon class="close"><Close /></el-icon> -->
                    <el-icon class="close" color="#fff" @click="delRulesList(index)"><Close /></el-icon>
                    <div class="keyword-label">
                        <div class="label">
                            {{item.type == 'KEY'? '关键字' : '礼物'}}
                        </div>

                        <div class="tag">
                            <span> {{item.type == 'KEY'? '关键字' : '礼物'}}</span>
                            <div class="tab-box">
                                <!-- <a-tag class="ml-2" :closable="true" color="#ECF5FF"  v-for="tag in item.tagList" @close="handleClose(tag)">
                                    {{ tag }}
                                </a-tag> -->
                                <el-tag  class="ml-2" style=" color: #BC81FC;" type="info" closable  effect="plain"  v-for="tag in item.tagList" @close="handleClose(tag)"> {{ tag }}</el-tag>
                                <EditInput :isCustomTag="false" @input="inputClick($event, index)" :label="item.type == 'KEY'? '关键字' : '礼物'" style="margin-top: -2px;" />
                            </div>
                        </div>
                    </div>
                    <div class="video-list">
                        <div class="video-header">
                            <span>回复视频列表</span>
                            <el-button style="margin-left: 10px;height: 20px;" color="#BC81FC" @click="addVideo(index)">+ 新增</el-button>
                        </div>
                        <div class="box-list">
                            <div class="list">
                                <TableItem  key="table-item2" v-for="video in item.videoList" :name="video.title" :time="`时长${video.length}分钟`" :id="video.id" :type="video.type" @iconClick="iconClick($event, video)"></TableItem>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

         </div>
         <div class="footer">
            <el-button color="#BC81FC" :loading="saveBtnLoading" style="color: #292331;width: 70px;" @click="saveVideoClick">保 存</el-button>
         </div>
    </div>
    <Dialog 
        :show="showDialog" 
        :title="'选择数字人'" 
        :width="isSelectPelple ? 300: 800"
        :isCloseTip="false" 
        :is-custom-footer="false"
        @on-close="showDialog = false;"
        @on-sure-click="showDialog = false"
    >
        <template #content>
           <div class="select" v-if="isSelectPelple">
                <SelectPeople @selectClick="selectClick"/>
           </div>
           <div  class="dialog-select" v-else>
                <videoSelect ref="videoSelectDialogRef" key="dialog" :is-get-list="true" :avatarName="avatarName" :isShowTitle="false" :select-list="rulesList[rulesIndex]?.videoList" @select="selectRulesVideo"/>
           </div>
        </template>
    </Dialog>
</template>
<script setup lang="ts">
import Header from '@/components/header/header.vue'
import Label from '../../main/components/label.vue'
import draggable from 'vuedraggable'
import SelectPeople from '@/components/selectPeople/index.vue'
import { ArrowDown, ArrowUp } from '@element-plus/icons-vue';
import { ref, onMounted, computed, nextTick } from 'vue'
import { Plus,Close } from '@element-plus/icons-vue';
import { useRouter, useRoute } from 'vue-router';
import { useBroadStore } from '@/store/broad'
import {PeopleInfo} from '@/models/home/broad'
import {getSelectPeopleInfo} from '@/service/broad';
import Dialog from '@/components/dialog/dialog.vue'
import videoSelect from '@/components/videoSelect/videoSelect.vue'
import EditInput from '@/components/editInput/input.vue'
import {saveVideo, getLiveVideoById} from '@/service/broad'
import {ElMessage, ElMessageBox} from 'element-plus'
import {to} from 'await-to-js'
const ic_amount = new URL('@/assets/imgs/ic_amount.png', import.meta.url).href
const ic_bo = new URL('@/assets/imgs/ic_bo.png', import.meta.url).href
const router = useRouter();
const route = useRoute();
const store = useBroadStore();
const answerOpen = ref<boolean>(false);
const showDialog = ref<boolean>(false)
const broadCastTitle = ref<string>('');
const selectPeopleId = ref<string | number>('');
const mainVideoRandom = ref<boolean>(true)
const isSelectPelple = ref<boolean>(false)
const rulesIndex = ref<number>(0)
const liveId = ref<string | number>('')
const isGetList = ref<boolean>(false)
const videoSelectDialogRef = ref(null)
const saveBtnLoading = ref<boolean>(false)
const peopleInfo = ref<PeopleInfo> ({
    coverSmall: '',
    videoCnt: '',
    videoLength: '',
    name: ''
})
const avatarName = ref<string>('')
const videoSelectRef = ref(null)
const isResetInfo = ref<boolean>(false)
const rulesList = ref<any[]>([
    // {type: 'keys', tagList: [], videoList: []}
])
const selectVideotListFirst = ref<any[]>([])
let timer = computed(() => {
   const time = selectVideotListFirst.value.reduce((acc, curr) => {
        acc += Number(curr.length);
        return acc;
    }, 0);
    return `${time}秒`
})

onMounted(() => {
    if (Array.isArray(route.query?.id)) {
        liveId.value = route.params?.id[0] || '';
    } else {
        liveId.value = route.query?.id || '';
    }
    if(liveId.value) {
        getLiveDetail(liveId.value)
    }

})
const getLiveDetail = async(id: string | number) => {
    const [err, res] = await to(getLiveVideoById({liveId: id}))
    if(err || !res.success) {
        return;
    }
    const {avatarId, mainVideoRandom: random, mainVideoList, title, replyRuleList} =  res.result;
    selectPeopleId.value = avatarId;
    mainVideoRandom.value = random;
    broadCastTitle.value = title;
    selectVideotListFirst.value = mainVideoList.map((val: any) => ({...val, type: 'delete'}))
    rulesList.value = replyRuleList.reduce((acc: any, curr: any) => {
        acc.push({
            type: curr.type, 
            tagList: curr.ruleContent ? JSON.parse(curr.ruleContent): [], 
            videoList: curr.videoList.map((val: any) => ({...val, type: 'delete'}))
        })
        return acc;
    }, [])

    await getPeopleInfo(selectPeopleId.value);
    avatarName.value =  peopleInfo.value.name || '';
    videoSelectRef.value && videoSelectRef.value.getVideoByAvatarName(peopleInfo.value.name)
}

const getPeopleInfo = async (id: string | number) => {
    const [err, data] = await to(getSelectPeopleInfo({avatarId: id}))
    if(err || !data.success) {
        return;
    }
    data.result.videoLength = convertMinutesToHoursAndMinutes(data.result.videoLength)
    peopleInfo.value = data.result;
    isGetList.value = true;

}
const addVideo = (index: number) => {
    showDialog.value = true;
    isSelectPelple.value = false;
     rulesIndex.value = index;
     nextTick(() => {
        videoSelectDialogRef.value && videoSelectDialogRef.value.getVideoByAvatarName(avatarName.value)
     })
}
const selectClick = async ({id}: { id: string | number}) => {
    if(isResetInfo.value) {
        rulesList.value = [];
        mainVideoRandom.value = true;
        selectVideotListFirst.value = [];
    }
    selectPeopleId.value = id;
    await getPeopleInfo(id);
    avatarName.value =  peopleInfo.value.name || '';
    videoSelectRef.value && videoSelectRef.value.getVideoByAvatarName(peopleInfo.value.name)
}
const selectPeopleClick = () => {
    if( !(peopleInfo.value.name && peopleInfo.value.coverSmall && peopleInfo.value.videoCnt)) {
        showDialog.value = true; isSelectPelple.value = true;
    }else {
        ElMessageBox.confirm(
            '重新选择数字人会清空所有选择数据，确认要继续吗？',
            '警告',
        {
        customClass: "messageStyle",
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        showCancelButton: false,
        type: 'warning',
        }
    )
        .then(() => {
            showDialog.value = true; 
            isSelectPelple.value = true;
            isResetInfo.value = true;
        })
        .catch(() => {
        })
    }
}
const convertMinutesToHoursAndMinutes = (seconds: number) => {
    if (isNaN(seconds) || seconds < 0) {
    return '请输入有效的秒数';
  }
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const remainingSeconds = seconds % 60;
  let formattedTime = '';
  if (hours > 0) {
    formattedTime += `${hours}小时`;
  }
  if (minutes > 0 || hours > 0) {
    formattedTime += `${minutes}分钟`;
  }
  formattedTime += `${remainingSeconds}秒`;
  return formattedTime;
}
const selectVideo = ({item}: {type?: string,item: any}) => {
    let info = JSON.parse(JSON.stringify(item))
    info.type = 'delete';
    if(!selectVideotListFirst.value.find(res => res.id == info.id)) {
        selectVideotListFirst.value.unshift(info)
    }
}
const backClick = () => {
    router.back();
    store.setIsList(true)
}

const inputClick = (label: string, index: number) => {
    rulesIndex.value = index;
    rulesList.value[index].tagList.push(label)
}
const addRules = (type: string) => {
    rulesList.value.push({type: type, tagList: [], videoList: []})
}

const delRulesList = (index: number) => {
    rulesList.value.splice(index, 1)
}
const selectRulesVideo = ({item}: {type?: string,item: any}) => {
    let info = JSON.parse(JSON.stringify(item))
    info.type = 'delete';
    if(!rulesList.value[rulesIndex.value].videoList.find((res: any) => res.id == info.id)) {
        rulesList.value[rulesIndex.value].videoList.unshift(info)
    }
}
const inputChange = ({label, type}: {label: string, type: string}) => {
    if(type == 'title') {
        broadCastTitle.value = label;
    }
}
const iconFirstClick = (type: string, item: any) => {
    if(type == 'delete') {
        selectVideotListFirst.value = selectVideotListFirst.value.filter(res => res.id !== item.id)
    }
}
const handleClose = (tag: string) => {
    rulesList.value[rulesIndex.value].tagList.splice( rulesList.value[rulesIndex.value].tagList.indexOf(tag), 1)
}
const iconClick = (type: string, item: any) => {
    if(type == 'delete'){
        rulesList.value[rulesIndex.value].videoList = rulesList.value[rulesIndex.value].videoList.filter((res: any) => res.id !== item.id)
    }
}
const saveVideoClick = async () => {
    if(!broadCastTitle.value) {
        ElMessage.error('请输入标题')
        return;
    }
    if(!selectPeopleId.value) {
        ElMessage.error('请选择数字人');
        return;
    }
    if(!selectVideotListFirst.value.length){
        ElMessage.error('主介绍人视频不能为空');
        return;
    }
    if(rulesList.value.some((res: any) => res.videoList.length == 0)){
        ElMessage.error('回复视频不能为空');
        return;
    }
    const list = rulesList.value.reduce((acc, curr) => {
      acc.push({type: curr.type, ruleContent: JSON.stringify(curr.tagList), videoIdList: curr.videoList.map((res: any) => res.id)})
      return acc
    }, [])
  
    const params = {
        id: liveId.value,
        avatarId: selectPeopleId.value,
        mainVideoRandom: mainVideoRandom.value,
        mainVideoIdList: selectVideotListFirst.value.map(res => res.id),
        replyRuleList: list,
        title: broadCastTitle.value
    }
    saveBtnLoading.value = true;
    const [err, res] = await to(saveVideo(params))
    saveBtnLoading.value = false;
    if(err || !res.success) {
        ElMessage.error(res.message)
        return;
    }
    ElMessage.success('保存成功');
    router.back();
    store.setIsList(true)
}
const answerIconClick = () => {
    answerOpen.value = !answerOpen.value;
}
</script>

<style scoped lang="css">
.edit-broad {
    color: #fff;
    overflow: auto;
    height: 100%;
}
.select-people {
    height: 8vh;
    width: 100%;
    background: #25212B;
    margin-top: 20px;
    border-radius: 10px;
    box-sizing: border-box;
    display: flex;
    /* align-items: center; */
    padding: 10px 20px;
    color: #8D8F97;
    /* justify-content: space-aroun; */
}
.title {
    font-weight: 600;
    font-size: 14px;
    color: #fff;
}
.no-people {
    height: 80px;
    width: 46px;
    position: relative;
    margin-right:10px;
    margin-left: 20px; 
    cursor: pointer;
}
.no-people .mark {
    background-color: rgb(0,0,0,0.8);
    height: 70px;
    position: absolute;
    left: 0;
    top: 0;
    width: 46px;
    display: flex;
    align-items: center;
    justify-content: center;
}
.no-people img{
    width: 46px;
}
.people {
    margin-left: 40px;
    display: flex;
    align-items: center;
    color: #fff;
    font-size: 20px;
}
.people img {
    width: 46px;
    margin-right:10px;
}
.video-num {
    flex: 1;
    display: flex;
    justify-content: center;
    /* height: 30px/; */
    padding-left: 100px;
    margin-right: 160px;
}

.main-video {
    width: 100%;
    height: 51vh;
    background: #25212B;
    margin-top: 20px;
    border-radius: 10px;
    padding: 20px 20px;
    display: flex;
    box-sizing: border-box;
    align-items: center;
}
.main-video .left {
    flex: 1;
    height: 100%;
}
.main-video .right {
    flex: 1;
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
    margin-top: -2px;
}
.main-video .table{
    padding: 20x 30px;
    display: flex;
    flex-direction: column;
    align-items: center;
}
.main-video .table-name{
   font-size: 14px;
   font-weight: 600;
   margin-bottom: 10px;
   color: #ABA9AD;
   /* margin-top: 10px; */
}
.table .list{
   height: 280px; 
   width: 80%;
   /* background-color: skyblue; */
   margin-right: 70px;
   padding-right: 20px;
   box-sizing: border-box;
   font-size: 12px;
   overflow: auto;
}
.right .table-list {
   height: 280px; 
   width: 80%;
   box-sizing: border-box;
   overflow: auto;
   padding-right: 20px;
}

.main-video .line {
    height: 80%;
    width: 2px;
    background: #3F3B42;
}
.right .table-header {
    display: flex;
    padding: 10px 0 20px 0px;
    justify-content: center;
}
.table-header > .switch > span{
    margin-right: 10px;
    font-size: 14px;
}
.right .table-header > span {
    font-size: 14px;
    margin: 0 40px 0 80px;
    display: flex;
    align-items: center;
}
:deep(.el-form-item__content) {
    width: 130px;
}
:deep(.btn){
    margin-left:20px;
}
.answer {
    width: 100%;
    background: #25212B;
    margin-top: 16px;
    border-radius: 10px;
    overflow: auto;
    padding: 20px;
    box-sizing: border-box;
}
.answer-title {
    display: flex;
    align-items: center;
    font-size: 16px;
    font-weight: 600;
}
.answer-title >.icon {
    margin-left: 10px;
    cursor: pointer;
}
.keyword-list{
    padding: 0 60px;
}

.keyword-list .keyword-header {
    margin: 30px 0;
}

.keyword-header  .btn {
    width: 140px
}
.keyword-header  .add-btn {
    margin: 0 40px 0 80px;
   
}
.keyword-list >.keyword-item {
    widows: 100%;
    height: 240px;
    border: 1px dashed #eee;
    display: flex;
    position: relative;
    margin-bottom: 20px;
}
.keyword-item .close {
    position: absolute;
    right: 10px;
    top: 10px;
}
.keyword-item .keyword-label {
    flex: 1;
    padding: 10px;
    box-sizing: border-box;
    display: flex;
    justify-content: center;
    justify-content: space-between;
}
.keyword-label .label {
    height: 100%;
    width: 80px;
    background-color: #453C4F;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    writing-mode: vertical-rl;
    letter-spacing: 10px;
    color: #B99EDE;
}
.keyword-label .tag{
    display: flex;
    align-items: center;
    flex-direction: column;
    justify-content: center;
    padding-top: 10px;
    margin: 0 30px;
    flex: 1;

}
.tag > span {
    font-size: 16px;
    margin-bottom: 10px;
}
.tag .tab-box {
    width: 100%;
    padding: 2px 10px;
    overflow-x: scroll;
    height: 420px;
    background-color: #453C4F;
    border-radius: 10px;
    display: flex;
    align-content: flex-start;
    flex-wrap: wrap;
    padding-left: 10px;
    box-sizing: border-box;
    margin-top: 10px;
    padding-top: 10px;
}
.tab-box .button-new-tag {
    margin-top: 6px;
    margin-left: 6px;
}
.tab-box .ml-2 {
    margin:0 6px 10px 6px;
}
.video-list{
    flex: 1;
    display: flex;
    justify-content: center;
    padding: 10px;
    flex-direction: column;
    align-items: center;
}
.video-list .video-header {
    font-size: 18px !important;
    margin: 6px 0;
}
.video-list .box-list{
    margin-top: 10px;
    padding: 10px 0;
    height: 90%;
    overflow: auto;
    width: 600px;
    background-color: #453C4F;
    border-radius: 10px;
   
}
.video-list .list {
    /* padding: 10px 0; */
    height: 100%;
    /* height: 100%;
    width: 400px;
    overflow: auto;
    background-color: #453C4F;
    border-radius: 10px; */
}

.select {
    height: 60vh;
    display: flex;
    justify-content: center;
}
.dialog-select {
    margin-top: 20px;
}
.footer {
    width: 100%;
    background: #25212B;
    margin-top: 20px;
    border-radius: 10px;
    height: 7vh;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    box-sizing: border-box;
    padding:0 2vw 0 1vw;
}
:deep(.footer .el-button) {
    font-size: 16px !important;
}
/* 整个滚动条 */
::-webkit-scrollbar {
  width: 4px; /* 设置滚动条的宽度 */
}

/* 滚动条轨道 */
::-webkit-scrollbar-track {
    display: none;
  background-color: #f1f1f1; /* 设置滚动条轨道的背景色 */
}

/* 滚动条滑块 */
::-webkit-scrollbar-thumb {
  background-color: #DDDEE0; /* 设置滚动条滑块的颜色 */
  border-radius: 6px; /* 设置滚动条滑块的圆角 */
}

/* 当鼠标悬停在滚动条上时，滑块的样式 */
::-webkit-scrollbar-thumb:hover {
  background-color: #B2B2B2; /* 设置鼠标悬停时滚动条滑块的颜色 */
}
:deep(.main-video .el-icon) {
 color: #fff;
}
/* :deep(.tab-box .el-icon) {
    color: #6BB3FF
} */
:deep(.dialog-select .el-icon) {
    color: #fff;
}
:deep(.dialog-select  .list, .table-name) {
    color: #fff;
}
:deep(.dialog-select .table-name) {
    color: #fff;
}
:deep(.dialog-select .el-input__inner) {
    background-color: #25212B;
    border: 0;
    color: #fff;
}
:deep(.dialog-select  .el-form-item__label){
    color: #fff;
}
:deep(.el-switch.is-checked .el-switch__core) {
    background-color: #BC81FC;
    border-color: #BC81FC;
}
</style>